import React from 'react';
import { Animated, Text, View, StyleSheet, Image, PanResponder, Easing, Dimensions } from 'react-native';
import { scaleSize } from './components/common';

export default class FadeInView extends React.Component {
  constructor(props) {
    super(props);
    this._handlePanResponderMove = this._handlePanResponderMove.bind(this);
    this._handlePanResponderEnd = this._handlePanResponderEnd.bind(this);
    this.state = {
      deviceWidth: Dimensions.get('window').width,
      translateX: new Animated.Value(0), // View移动距离
      sIndex: 0, // 当前页
      isPrevMove: false, // 是否往上一页移动
      swiperWidth: scaleSize(610), // View宽度
      imgWidth: scaleSize(540), // 内容宽度
      imgHeight: scaleSize(540), // 内容高度
      moveLeft: '', // 向左移动距离
      defaultOpacity: 0.5, // 默认透明度
      defaultScale: 0.6, // 默认缩放比例1-0.6区间
      imgArr: [
        {
          imgUrl: 'https://img.alicdn.com/imgextra/i2/1030778510/TB2ZViXsnJYBeNjy1zeXXahzVXa_!!1030778510.jpg_430x430q90.jpg',
          opacity: 1,
          zIndex: 0,
          translateX: 0,
          scale: 1
        },
        {
          imgUrl: 'https://img.alicdn.com/imgextra/i1/2096542875/TB1iu.Fb56guuRjy1XdXXaAwpXa_!!0-item_pic.jpg_430x430q90.jpg',
          opacity: 1,
          zIndex: 0,
          translateX: 0,
          scale: 1
        },
        {
          imgUrl: 'https://img.alicdn.com/imgextra/i3/1795616675/TB23vZFg0rJ8KJjSspaXXXuKpXa-1795616675.jpg_430x430q90.jpg',
          opacity: 1,
          zIndex: 0,
          translateX: 0,
          scale: 1
        },
      ]
    };
  }

  componentWillMount() {
    // 计算初始化页面布局
    let arr = this.state.imgArr;
    for (let i = 0; i < arr.length; i++) {
      arr[i].zIndex = arr.length - i;
    }

    this.setState({
      moveLeft: (scaleSize(750) - this.state.imgWidth)/2 + this.state.imgWidth,
      imgArr: arr
    })
    console.log(this.state.moveLeft);
    console.log(arr);
    // 绑定手势事件
    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: (evt, gestureState) => true,
      onMoveShouldSetPanResponder: (evt, gestureState) => true,
      onPanResponderGrant: this._handlePanResponderGrant,
      onPanResponderMove: this._handlePanResponderMove,
      onPanResponderRelease: this._handlePanResponderEnd,
      onPanResponderTerminate: this._handlePanResponderEnd,
    });
  }

  _handlePanResponderGrant(evt, gestureState) {
    console.log('start');
  }
  _handlePanResponderMove(evt, gestureState) {
    console.log('move');
    console.log(gestureState.dx)
    console.log(gestureState.dy)
    if (Math.abs(gestureState.dx) > Math.abs(gestureState.dy)) {
      console.log('横向滑动')
      if (gestureState.dx > 0 && this.state.sIndex > 0) {
        this.setState({
          isPrevMove: true
        })
        Animated.spring(
          this.state.translateX,
          {
            toValue: gestureState.dx - this.state.moveLeft * this.state.sIndex,
            duration: 0,
          }
        ).start(); 
      } else if (gestureState.dx < 0 && this.state.sIndex < this.state.imgArr.length - 1) {
        this.setState({
          isPrevMove: false
        })
        Animated.spring(
          this.state.translateX,
          {
            toValue: gestureState.dx - this.state.moveLeft * this.state.sIndex,
            duration: 0,
          }
        ).start(); 
      }
    } else {
      console.log('纵向滑动')
    }
  }
  _handlePanResponderEnd(evt, gestureState) {
    console.log('end');
    console.log(gestureState.dx)
    console.log(gestureState.dy)

    // if (Math.abs(gestureState.dx) > Math.abs(gestureState.dy)) {
      if (gestureState.dx > this.state.deviceWidth/2 && this.state.sIndex > 0) {
        Animated.timing(
          this.state.translateX,
          {
            toValue: this.state.moveLeft - this.state.moveLeft * this.state.sIndex,
            duration: 300,
            easing: Easing.in()
          }
        ).start(() => {
          let index = this.state.sIndex - 1;
          this.setState({
            sIndex: index,
            isPrevMove: false
          })
        })
      } else if (gestureState.dx < -this.state.deviceWidth/2 && this.state.sIndex < this.state.imgArr.length - 1) {
        Animated.timing(
          this.state.translateX,
          {
            toValue: this.state.moveLeft * -1 - this.state.moveLeft * this.state.sIndex,
            duration: 300,
            easing: Easing.in()
          }
        ).start(() => {
          let index = this.state.sIndex + 1;
          this.setState({
            sIndex: index,
            isPrevMove: false
          })
        })
      } else {
        console.log('复原')
        Animated.timing(
          this.state.translateX,
          {
            toValue: (this.state.moveLeft * (this.state.sIndex - 1) + this.state.moveLeft) * -1,
            duration: 300,
            easing: Easing.in()
          }
        ).start()
      }
    // }
  }

  render() {
    let { imgArr, translateX, swiperWidth, imgWidth, imgHeight, moveLeft, sIndex, defaultScale, isPrevMove, defaultOpacity} = this.state;
    console.log('sIndex:', sIndex);
    
    let transformArr = [];
    let opacityArr = [];
    let consoleArr = [];
    // 计算位移
    for (let i = 0; i < imgArr.length; i++) {
      let scale = 1 - ((1 - defaultScale)/(imgArr.length - 1) * Math.abs(i - sIndex - 1));
      let _translateX = (swiperWidth - imgWidth)/(imgArr.length - 1) * Math.abs(i - sIndex - 1) + (imgWidth - scale * imgWidth)/2;

      let scale2 = 1 - ((1 - defaultScale)/(imgArr.length - 1) * Math.abs(i - sIndex));
      let _translateX2 = (swiperWidth - imgWidth)/(imgArr.length - 1) * Math.abs(i - sIndex) + (imgWidth - scale2 * imgWidth)/2;

      let transform;
      let opacity;
      if (i == sIndex) {
        if (isPrevMove) {
          consoleArr.push([0, _translateX, 1, scale, 0, defaultOpacity]);
          transform = [{translateX: translateX.interpolate({
            inputRange: [-moveLeft * sIndex, -moveLeft * (sIndex - 1)],
            outputRange: [0, _translateX],
          })}, {scaleX: translateX.interpolate({
            inputRange: [-moveLeft * sIndex, -moveLeft * (sIndex - 1)],
            outputRange: [1, scale],
          })}, {scaleY: translateX.interpolate({
            inputRange: [-moveLeft * sIndex, -moveLeft * (sIndex - 1)],
            outputRange: [1, scale],
          })}];
          opacity = translateX.interpolate({
            inputRange: [-moveLeft * sIndex, -moveLeft * (sIndex - 1)],
            outputRange: [0, defaultOpacity]
          });
        } else {
          consoleArr.push([-moveLeft, 0, scale, 1, 0, 0]);
          transform = [{translateX: translateX.interpolate({
            inputRange: [-moveLeft * (sIndex + 1), -moveLeft * sIndex],
            outputRange: [-moveLeft, 0],
          })}, {scaleX: translateX.interpolate({
            inputRange: [-moveLeft * (sIndex + 1), -moveLeft * sIndex],
            outputRange: [scale, 1],
          })}, {scaleY: translateX.interpolate({
            inputRange: [-moveLeft * (sIndex + 1), -moveLeft * sIndex],
            outputRange: [scale, 1],
          })}];
          opacity = translateX.interpolate({
            inputRange: [-moveLeft * (sIndex + 1), -moveLeft * sIndex],
            outputRange: [0, 0]
          });
        }

      } else if (i > sIndex) {
        consoleArr.push([_translateX, _translateX2, scale, scale2, 0, defaultOpacity]);
        transform = [{translateX: translateX.interpolate({
          inputRange: [-moveLeft * (sIndex + 1), -moveLeft * sIndex],
          outputRange: [_translateX, _translateX2],
        })}, {scaleX: translateX.interpolate({
          inputRange: [-moveLeft * (sIndex + 1), -moveLeft * sIndex],
          outputRange: [scale, scale2],
        })}, {scaleY: translateX.interpolate({
          inputRange: [-moveLeft * (sIndex + 1), -moveLeft * sIndex],
          outputRange: [scale, scale2],
        })}];
        if (i - sIndex == 1 && !isPrevMove) {
          opacity = translateX.interpolate({
            inputRange: [-moveLeft * (sIndex + 1), -moveLeft * sIndex],
            outputRange: [0, defaultOpacity]
          });
        } else {
          opacity = translateX.interpolate({
            inputRange: [-moveLeft * (sIndex + 1), -moveLeft * sIndex],
            outputRange: [defaultOpacity, defaultOpacity]
          });
        }
        
      } else {
        console.log("-moveLeft: ", -moveLeft);
        consoleArr.push([-moveLeft * (sIndex + 1 - i), -moveLeft * (sIndex - i), scale, scale2, 0, 0]);
        transform = [{translateX: translateX.interpolate({
          inputRange: [-moveLeft * (sIndex + 1), -moveLeft * sIndex],
          outputRange: [-moveLeft * (sIndex + 1 - i), -moveLeft * (sIndex - i)],
        })}, {scaleX: translateX.interpolate({
          inputRange: [-moveLeft * (sIndex + 1), -moveLeft * sIndex],
          outputRange: [scale, scale2],
        })}, {scaleY: translateX.interpolate({
          inputRange: [-moveLeft * (sIndex + 1), -moveLeft * sIndex],
          outputRange: [scale, scale2],
        })}];
        opacity = translateX.interpolate({
          inputRange: [-moveLeft * (sIndex + 1), -moveLeft * sIndex],
          outputRange: [0, 0]
        });
      }
      transformArr.push(transform);
      opacityArr.push(opacity);
    }
    console.log(consoleArr);
    console.log(opacityArr[0]);
    console.log(transformArr);

    return (
      <Animated.View                
        style={{...styles.container, width: swiperWidth}}
        {...this._panResponder.panHandlers}
      >
      {
        imgArr.map((item, index) => {
          return <Animated.View style={{...styles.transformView, zIndex: item.zIndex, width: imgWidth, height: imgHeight, transform: transformArr[index]}} key={index}>
            <Image
              style={{width: imgWidth, height: imgHeight}}
              source={{uri: item.imgUrl}}
            />
            <Animated.View style={{...styles.cover, opacity: opacityArr[index], width: imgWidth, height: imgHeight}}/>
          </Animated.View>
        })
      }
      </Animated.View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
    position: 'relative',
  },
  transformView: {
    position: 'absolute',
    left: 0,
  },
  cover: {
    position: 'absolute',
    left: 0,
    top: 0,
    backgroundColor: '#ffffff',
    // opacity:0.8
  }
});